﻿package com.sshc625.net {
	import flash.events.AsyncErrorEvent;
	import flash.events.EventDispatcher;
	import flash.events.NetStatusEvent;
	import flash.events.EventDispatcher;
	import flash.net.NetConnection;
	import flash.net.Responder;
	import flash.net.ObjectEncoding;

	import com.sshc625.events.ServiceEvent;

	/**
	 * @author sshc625
	 */
	public class NetConnectionService extends EventDispatcher implements IService {
		/**
		 * Private properties
		 */
		private var _connect:NetConnection;
		private var _service:String;

		/**
		 * NetConnectionService
		 * @param       Location of the service.
		 * @param       Service to execute.
		 * @param       ObjectEncoding used to connect to the IService, ObjectEncoding.DEFAULT by default.
		 */
		public function NetConnectionService( gateway:String, service:String, objectEncoding:uint = ObjectEncoding.DEFAULT ) {
			// Create a connection to the IService gateway
			this._connect = new NetConnection();
			this._connect.objectEncoding = objectEncoding;
			this._connect.connect( gateway );

			this._service = service;
		}

		/**
		 * Executes the IService
		 * @param       [optional] Arguments send to the IService
		 */
		public function execute( ... args ):void {
			var myResponder:Responder = new Responder( this.onResult, this.onFault );
			var myArguments:Array = [ this._service, myResponder ];
			myArguments = myArguments.concat( args );
			this._connect.call.apply( this._connect, myArguments );
		}

		/**
		 * Executes when the IService responds succesfully
		 * @param       Result of the call
		 *
		 */
		protected function onResult( result:Object ):void {
			var evt:ServiceEvent = new ServiceEvent( ServiceEvent.RESULT );
			evt.result = result;
			this.dispatchEvent( evt );

			this.dispose();
		}

		/**
		 * Executes when an error occured while executing the IService
		 * @param       Object containing  information about the error
		 *
		 */
		protected function onFault( info:Object ):void {
			if ( this.hasEventListener( ServiceEvent.FAULT )) {
				var evt:ServiceEvent = new ServiceEvent( ServiceEvent.FAULT );
				evt.errorCode = info.toString();
				this.dispatchEvent( evt );
			} else {
				throw new Error( "SERVICE_FAULT" );

			}
			this.dispose();
		}

		/**
		 * Disposes the NetConnectionService
		 */
		protected function dispose():void {
			this._connect.close();

			// nullify objects
			this._connect = null;
			this._service = null;
		}
	}
}